package com.wenzhoujie;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.wenzhoujie.library.title.SDTitleTwoRightButton.SDTitleTwoRightButtonListener;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.wenzhoujie.adapter.ShareDetailCommentAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.ApkConstant;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.fragment.ShareDetailFirstFragment;
import com.wenzhoujie.fragment.ShareDetailSecondFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.CommentlistItemModel;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.ShareItemImageModel;
import com.wenzhoujie.model.ShareItemModel;
import com.wenzhoujie.model.act.BaseActModel;
import com.wenzhoujie.model.act.CommentlistActModel;
import com.wenzhoujie.model.act.ShareActModel;
import com.wenzhoujie.umeng.UmengSocialManager;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * 分享详情
 * 
 * @author js02
 * 
 */
public class ShareDetailActivity extends BaseActivity implements OnClickListener
{
	/** share_id */
	public static final String EXTRA_SHARE_ID = "extra_share_id";

	/** page_id */
	public static final String EXTRA_PAGE_ID = "extra_page_id";

	/** share_list */
	public static final String EXTRA_SHARE_LIST = "extra_share_list";

	@ViewInject(id = R.id.act_share_detail_ll_linear_vis)
	private LinearLayout mLlLinearVis = null;

	@ViewInject(id = R.id.act_share_detail_ptrlv_all)
	private PullToRefreshScrollView mPtrlvAll = null;

	@ViewInject(id = R.id.act_share_detail_fl_first)
	private FrameLayout mFlFirst = null;

	@ViewInject(id = R.id.act_share_detail_fl_second)
	private FrameLayout mFlSecond = null;

	@ViewInject(id = R.id.act_share_detail_ll_comment)
	private LinearLayout mLlComment = null; // 评论布局
	@ViewInject(id = R.id.act_share_detail_tv_comment_count)
	private TextView mTvCommentcount = null;

	@ViewInject(id = R.id.act_share_detail_ll_like)
	private LinearLayout mLlLike = null; // 喜欢布局
	@ViewInject(id = R.id.act_share_detail_iv_like)
	private ImageView mIvLike = null;
	@ViewInject(id = R.id.act_share_detail_tv_likes_count)
	private TextView mTvLikeCount = null;

	@ViewInject(id = R.id.act_share_detail_ll_share)
	private LinearLayout mLlShare = null; // 分享布局

	@ViewInject(id = R.id.act_share_detail_lv_comments)
	private ListView mLvComments = null;

	private ShareDetailCommentAdapter mAdapter = null;
	private ShareItemModel mShareItemModel = null;
	private List<CommentlistItemModel> mListCommentlistItemModel = new ArrayList<CommentlistItemModel>();

	private ShareDetailFirstFragment mFragFirst = null;
	private ShareDetailSecondFragment mFragSecond = null;

	private String uid;

	private String share_id = null;
	private int pageid = 0;
	private ArrayList<String> share_list = null;

	private int mCurPage = 1;
	private int mTotalPage = -1;

	private String content;

	private void setShareItemModel(ShareItemModel model)
	{
		this.mShareItemModel = model;
		if (model != null)
		{
			this.uid = model.getUid();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_TWO_RIGHT_BUTTON);
		setContentView(R.layout.act_share_detail);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		initTitle();
		getIntentData();
		bindDefaultData();
		registeClick();
		initPullToRefreshScrollView();
	}

	private void initTitle()
	{
		mTitleTwoRightBtns.setRightImage1(R.drawable.ico_priv);
		mTitleTwoRightBtns.setRightImage2(R.drawable.ico_next);
		mTitleTwoRightBtns.setmListener(new SDTitleTwoRightButtonListener()
		{

			@Override
			public void onRightButton2CLick_SDTitleTwoRightButton(View v)
			{
				clickDetailNext();
			}

			@Override
			public void onRightButton1CLick_SDTitleTwoRightButton(View v)
			{
				clickDetailBack();
			}

			@Override
			public void onLeftButtonCLick_SDTitleTwoRightButton(View v)
			{
				finish();
			}
		});
	}

	private void initPullToRefreshScrollView()
	{
		mPtrlvAll.setMode(Mode.BOTH);
		mPtrlvAll.setOnRefreshListener(new OnRefreshListener2<ScrollView>()
		{
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView)
			{
				requestShareDetail();
				refreshComment();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView)
			{
				loadMoreComment();
			}
		});
		mPtrlvAll.setRefreshing();
	}

	private void refreshComment()
	{
		mCurPage = 1;
		requestComment(false);
	}

	private void loadMoreComment()
	{
		if (++mCurPage > mTotalPage && mTotalPage != -1)
		{
			mPtrlvAll.onRefreshComplete();
			SDToast.showToast("没有更多数据了");
		} else
		{
			requestComment(true);
		}
	}

	private void requestShareDetail()
	{
		if (share_id != null)
		{
			RequestModel model = new RequestModel();
			model.put("act", "share");
			if (AppHelper.isLogin())
			{
				model.put("email", AppHelper.getLocalUser().getUser_name());
				model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			}
			model.put("share_id", share_id);
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					ShareActModel actModel = JsonUtil.json2Object(responseInfo.result, ShareActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						if (actModel.getResponse_code() == 1)
						{
							setShareItemModel(actModel.getItem());
							addFragments(mShareItemModel);
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					AppHelper.hideLoadingDialog();
				}
			};

			InterfaceServer.getInstance().requestInterface(model, handler);
		}

	}

	/**
	 * 从intent获取数据
	 */
	private void getIntentData()
	{
		Intent intent = getIntent();
		if (intent.hasExtra(EXTRA_SHARE_ID))
		{
			share_id = intent.getStringExtra(EXTRA_SHARE_ID);
		}
		if (intent.hasExtra(EXTRA_PAGE_ID))
		{
			pageid = (Integer) intent.getSerializableExtra(EXTRA_PAGE_ID);
		}
		if (intent.hasExtra(EXTRA_SHARE_LIST))
		{
			share_list = intent.getStringArrayListExtra(EXTRA_SHARE_LIST);
		}

		changeTitleState();

		if (AppHelper.isEmptyString(share_id))
		{
			SDToast.showToast("分享id为空");
			finish();
		}

	}

	private void bindDefaultData()
	{
		mAdapter = new ShareDetailCommentAdapter(mListCommentlistItemModel, this);
		mLvComments.setAdapter(mAdapter);
	}

	private void requestComment(final boolean isLoadMore)
	{
		if (share_id != null)
		{
			RequestModel model = new RequestModel();
			model.put("act", "commentlist");
			if (AppHelper.isLogin())
			{
				model.put("email", AppHelper.getLocalUser().getUser_name());
				model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			}
			model.put("share_id", share_id);
			model.put("page", mCurPage);
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					CommentlistActModel actModel = JsonUtil.json2Object(responseInfo.result, CommentlistActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						if (actModel.getPage() != null)
						{
							mCurPage = actModel.getPage().getPage();
							mTotalPage = actModel.getPage().getPage_total();
						}
						SDViewUtil.updateAdapterByList(mListCommentlistItemModel, actModel.getItem(), mAdapter, isLoadMore);
					}
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					AppHelper.hideLoadingDialog();
					mPtrlvAll.onRefreshComplete();
					SDViewUtil.resetListViewHeightBasedOnChildren(mLvComments);
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}

	}

	/**
	 * 绑定底部数据
	 * 
	 * @param shareDetailModel
	 */
	private void bindBottomData(ShareItemModel shareDetailModel)
	{
		if (shareDetailModel != null)
		{
			// 评论数
			Integer commentCount = shareDetailModel.getComment_count();
			if (commentCount != null)
			{
				mTvCommentcount.setText(commentCount + "评论");
			} else
			{
				mTvCommentcount.setText("0评论");
				SDToast.showToast("未找到评论数量");
			}

			// 喜欢数
			Integer collectCount = shareDetailModel.getCollect_count();
			if (collectCount != null)
			{
				mTvLikeCount.setText(collectCount + "喜欢");
			} else
			{
				mTvLikeCount.setText("0喜欢");
				SDToast.showToast("未找到喜欢数量");
			}

			// 是否喜欢
			Integer isCollect = shareDetailModel.getIs_collect_share();
			if (isCollect != null)
			{
				if (isCollect == 0)
				{
					mIvLike.setImageResource(R.drawable.ico_collect0);
				} else if (isCollect == 1)
				{
					mIvLike.setImageResource(R.drawable.ico_collect);
				} else
				{
					mIvLike.setImageResource(R.drawable.ico_collect0);
					SDToast.showToast("未知的喜欢状态：" + isCollect);
				}
			} else
			{
				mIvLike.setImageResource(R.drawable.ico_collect0);
			}
		}
	}

	private void changeTitleState()
	{
		if (share_list != null && share_list.size() > 0)
		{
			mTitleTwoRightBtns.mIvRight1.setVisibility(View.VISIBLE);
			mTitleTwoRightBtns.mIvRight2.setVisibility(View.VISIBLE);
			mTitleTwoRightBtns.setTitleTop((pageid + 1) + "/" + share_list.size());
		} else
		{
			mTitleTwoRightBtns.mIvRight1.setVisibility(View.GONE);
			mTitleTwoRightBtns.mIvRight2.setVisibility(View.GONE);
			mTitleTwoRightBtns.setTitleTop("详情");
		}
	}

	/**
	 * 添加fragment和绑定顶部数据
	 */
	private void addFragments(ShareItemModel actModel)
	{
		mFragFirst = new ShareDetailFirstFragment();
		mFragFirst.setShareListDetailsModel(actModel);
		replaceFragment(mFragFirst, R.id.act_share_detail_fl_first);

		mFragSecond = new ShareDetailSecondFragment();
		mFragSecond.setmShareItemModel(actModel);
		replaceFragment(mFragSecond, R.id.act_share_detail_fl_second);

		bindBottomData(actModel);

	}

	private void registeClick()
	{

		mLlComment.setOnClickListener(this);
		mLlLike.setOnClickListener(this);
		mLlShare.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.act_share_detail_ll_comment:
			clickComments();
			break;

		case R.id.act_share_detail_ll_like:
			clickLikes();
			break;

		case R.id.act_share_detail_ll_share:
			clickShare();
			break;

		default:
			break;
		}
	}

	private void clickDetailNext()
	{
		if (pageid + 1 < share_list.size())
		{
			pageid = pageid + 1;
			share_id = share_list.get(pageid);
			changeTitleState();
			requestShareDetail();
		} else
		{
			Toast.makeText(ShareDetailActivity.this, "已经到最后一页", Toast.LENGTH_SHORT).show();
		}

	}

	private void clickDetailBack()
	{

		if (pageid == 0)
		{
			Toast.makeText(ShareDetailActivity.this, "已经到最前一页", Toast.LENGTH_SHORT).show();
		} else
		{
			pageid = pageid - 1;
			share_id = share_list.get(pageid);
			changeTitleState();
			requestShareDetail();
		}

	}

	/**
	 * 喜欢
	 */
	private void clickLikes()
	{
		requestLikes();
	}

	/**
	 * 发表评论
	 */
	private void clickComments()
	{

		if (!AppHelper.isLogin()) // 未登录
		{
			startActivity(new Intent(getApplicationContext(), LoginNewActivity.class));
		} else
		{
			Dialog d = new MyDialog(ShareDetailActivity.this, R.style.MyDialog);
			d.show();

		}
	}

	/**
	 * 自定义对话框的类
	 */
	class MyDialog extends Dialog
	{

		public MyDialog(Context context, int theme)
		{
			super(context, theme);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState)
		{
			super.onCreate(savedInstanceState);
			this.setContentView(R.layout.dialog);

			// 退出按钮和返回按钮
			Button submit_button, return_button;
			final EditText content_text;

			// 初始化
			submit_button = (Button) findViewById(R.id.submit_button);
			return_button = (Button) findViewById(R.id.return_button);
			content_text = (EditText) findViewById(R.id.dlg_input_content);

			// 发表
			submit_button.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					if (content_text.getText().toString() == null || "".equals(content_text.getText().toString()))
					{
						Toast.makeText(ShareDetailActivity.this, "点评内容为空,发布失败!", Toast.LENGTH_LONG).show();
					} else
					{
						content = content_text.getText().toString();
						requestAddComment(share_id);
						dismiss();
						mListCommentlistItemModel.clear();
						mPtrlvAll.setRefreshing();
					}
				}
			});

			// 返回
			return_button.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					// 关闭对话框
					dismiss();
				}
			});
		}

	}

	/**
	 * 发表评论接口
	 */
	protected void requestAddComment(String share_id)
	{
		RequestModel model = new RequestModel();
		model.put("act", "addcomment");
		LocalUserModel user = App.getApplication().getmLocalUser();
		if (user != null)
		{
			model.put("email", user.getUser_name());
			model.put("pwd", user.getUser_pwd());
		}
		model.put("share_id", share_id);
		model.put("source", "来自android客户端");
		model.put("is_relay", 1);
		model.put("parent_id", 0);
		model.put("content", content);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				BaseActModel actModel = JsonUtil.json2Object(responseInfo.result, BaseActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (actModel.getResponse_code() == 1)
					{
						int status = SDTypeParseUtil.getIntFromString(actModel.getStatus(), 0);
						if (status == 1)
						{
							refreshComment();
						} else if (status == 0)
						{
							SDToast.showToast("发表评论失败");
						}
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{

			}
		};

		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	/**
	 * 喜欢接口
	 */
	private void requestLikes()
	{
		if (AppHelper.isEmptyString(share_id))
		{
			return;
		}

		if (!AppHelper.isLogin())
		{
			startActivity(new Intent(this, LoginNewActivity.class));
			return;
		}

		if (AppHelper.getLocalUser().getUser_id().equals(uid))
		{
			SDToast.showToast("不能喜欢自己");
			return;
		}

		RequestModel model = new RequestModel();
		model.put("act", "share");
		model.put("act_2", "collect");
		model.put("email", AppHelper.getLocalUser().getUser_name());
		model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
		model.put("share_id", share_id);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				ShareActModel actModel = JsonUtil.json2Object(responseInfo.result, ShareActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (actModel.getResponse_code() == 1)
					{
						setShareItemModel(actModel.getItem());
						addFragments(mShareItemModel);
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				AppHelper.hideLoadingDialog();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);
	}

	/**
	 * 分享
	 */
	private void clickShare()
	{
		if (mShareItemModel != null)
		{
			String content = mShareItemModel.getShare_content();
			String imageUrl = null;
			String clickUrl = null;

			List<ShareItemImageModel> listImage = mShareItemModel.getImgs();
			if (listImage != null && listImage.size() > 0)
			{
				ShareItemImageModel image = listImage.get(0);
				if (image != null)
				{
					imageUrl = image.getImg();
				}
			}
			if (!TextUtils.isEmpty(content))
			{
				if (content.contains("http://"))
				{
					clickUrl = content.substring(content.indexOf("http://"));
				} else
				{
					clickUrl = ApkConstant.SERVER_API_URL_PRE + ApkConstant.SERVER_API_URL_MID;
				}
			}

			UmengSocialManager.openShare("分享", content, imageUrl, clickUrl, this, new SnsPostListener()
			{

				@Override
				public void onStart()
				{

				}

				@Override
				public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2)
				{

				}
			});

		}
	}

}